package com.gopay.webtest.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.gopay.webtest.xml.XmlDao;

@Repository("initParam")
public class InitParamfilter implements Filter {
    private String KEY ="11111aaaaa";
    
    private static Map<String, String> map = null;
    private static Map<String, String> devUrl = null;
    
    @Autowired
    public InitParamfilter(@Qualifier(value = "xmlDao") XmlDao xmlDao) {
        try {
            map = xmlDao.readData4Map("url", "url");
            devUrl = xmlDao.readEvnNode("url", map.get("defualt"));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void destroy() {

    }
    
    /**
     * 初始化参数
     */
    @Override
    public void doFilter(ServletRequest re, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) re;
        if (request.getSession().getAttribute("gopay_webtest_URL_Name") == null) {
            // 获取cookie
            String name = (String) map.get("defualt");
            // 读取默认地址
            String defualt = (String) map.get("defualt");
            name = defualt;
            String key = KEY;
            request.getSession().setAttribute("gopay_webtest_URL", devUrl);
            request.getSession().setAttribute("gopay_webtest_URL_Name", name);
            request.getSession().setAttribute("gopay_webtest_key", key);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
